'use strict';

var Router = require('koa-router'),
  koajwt = require('koa-jwt'),
  debug = require('debug'),
  log = debug('yozh:config:log'),
  error = debug('yozh:config:error'),
  verbose = debug('yozh:config:verbose'),
  config = require('./config'),
  tools = require('../lib/tools'),
  token = require('../middlewares/token'),
  permission = require('../middlewares/permission'),
  roleService = require('../modules/role/role.service');

var routes = function routes(app) {
  var router = new Router();

  app
    .use(router.routes())
    .use(router.allowedMethods());

  router.get('/', function* (next) {
    log(this.query, this.youzhe);
    this.body = 'index';
    this.state.skipChectToken = true;
    yield next;
  });

  require('../modules/base/base.route')(app);
  require('../modules/user/access.route')(app);
  require('../modules/user/authorization.route')(app);
  require('../modules/user/formtoken.route')(app);
  require('../modules/user/restoration.route')(app);
  // require('./my_wechat')(app);
  require('../modules/wechat/wechat.route')(app);

  // Custom 401 handling
  /*app.use(function *(next){
    try {
      yield next;
    } catch (err) {
      if (401 == err.status) {
        this.status = 401;
        this.body = '401 Unauthorized - Protected resource,\
         use Authorization header to get access\n';
      } else {
        throw err;
      }
    }
  });*/

  // Unprotected middleware
  /*app.use(function *(next){
    if (this.url.match(/^\/public/)) {
      this.body = 'unprotected\n';
    } else {
      yield next;
    }
  });*/

  // Middleware below this line is only reached if JWT token is valid
  // app.use(koajwt({secret: 'youzhe', debug: true}));
  // app.use(token({tools: tools, cache: tokenCache}));

  // decode token and set to this.state;
  // app.use(permission({
  //   tools: tools,
  //   roleService: roleService,
  //   constants: config.constants}
  // ));

  require('../modules/article/article.route')(app);
  require('../modules/log/log.route')(app);
  require('../modules/menu/menu.route')(app);
  require('../modules/part/part.route')(app);
  require('../modules/role/role.route')(app);
  require('../modules/topic/topic.route')(app);
  require('../modules/user/user.route')(app);

};

module.exports = routes;
